<template>
     <qh-page-view :title="title">
          <view class="search-box">
               <view class="search-content flex-cn">
                    <text class="qh-rt-single qh-rt-a-zu2432 search-icon"></text>
                    <input class="search-input" 
                         type="text" 
                         :focus="isFocus" 
                         v-model="searchForm.search"
                         placeholder="请输入商品名称" 
                         placeholder-class="pl" 
                         @focus="handleOnfocus"  
                         @blur="showHistory = false"
                         confirm-type="search"
                         @confirm="searchData"/>
                    <view class="search-btn flex-cn-cn" @click="searchData">搜索</view>
               </view>
          </view>
          <searcHistory
            v-model="showHistory"
            :top-distance="88"
            @doSearch="handleSearch"
            ref="historyPopup"
        />

          <view class="flex-column-100">
               <scroll-view scroll-y="true" class="scroll-view" :lower-threshold="100" :show-scrollbar="false" @scrolltolower="getGoodsList"
                    refresher-enabled @refresherrefresh="pullDownRefresh" :refresher-triggered="isRefresh"
                    refresher-background="transparent">
                    <view class="scroll-view-content">
                         <!-- 商品列表搜索 VIP4-->
                         <view class="goods-list-box  flex-spb flex-wrap">
                              <waterfallsFlow  ref="WaterfallRef" @updateSKU="generateSKU"
                                  :wfList="goodsList" :updateNum="searchForm.page">
                              </waterfallsFlow>
                              <view class="flex-cn-cn" style="width: 100%;height: 60rpx;">
                                   <view v-if="canLoad && isLoading" class="bottom-message flex-cn-cn">加载中...</view>
                                   <view v-if="!canLoad && !isLoading" class="flex-cn-cn bottom-message">
                                        <view class="line"></view>
                                        <text class="mar_l_10 mar_r_10">没有更多了</text>
                                        <view class="line"></view>
                                   </view>
                              </view>
                         </view>
                    </view>
               </scroll-view>
          </view>

          <shopping-pushpins></shopping-pushpins>
          <!-- 选择规格弹窗 -->
          <block v-if="showSelectSku">
               <choose-sku :sku="sku" :goodsinfo="goods" goodsType="1" @close="closeSku"></choose-sku>
          </block>

          <SkuDetailsCard ref="popupComponent" :goodsinfo="goods" :BoxStyle="1"></SkuDetailsCard>
          
      



     </qh-page-view>
     
</template>

<script>
const app = getApp().globalData;
//sku的组件
import SkuDetailsCard from '@/components/skuDetails/skuDetails.vue'
//历史搜索的组件
import searcHistory from './search_history/search_history.vue'
export default {
     components: {
          SkuDetailsCard,
          searcHistory
     },
     data() {
          return {
               goods_id_gather: "", //商家券适合的商品id 、会员优惠券指定分类，指定商品id集合
               showHistory:false,  //search的状态值
               goodsChecked: [],
               animations: [],
               animationIndex: null,
               indexes: [],
               isFocus: false,
               title: "",
               goodsList: [],
               isRefresh: false,
               isLoading: false,
               canLoad: true,
               searchForm: {
                    search: "",
                    person1: "",
                    person2: "",
                    person3: "",
                    page: 1,
                    limit: 10,
               },
               showSelectSku: false,
               goods: {},
               sku: {},
               class_id:"",  //分类ID
          };
     },
     /**
      * @param {Object} options
      * name		分类名称
      * type		分类级别  1、2、3 不传默认为1
      * id		分类id
      */
     async onLoad(options) {
          await this.$onLaunched;

          if(options.mycoupon == '2'){
          this.goods_id_gather =  options.goods_id_gather
          // 使用 await 确保 getGoodsList 完成
          await this.getGoodsList()
          }

          if(options.mycoupon == '3'){
          this.class_id =  options.class_id
          // 使用 await 确保 getGoodsList 完成
          await this.getGoodsList()
          }

          if (options.search == 1) {
               this.$nextTick(() => {
                    this.isFocus = true;
               });
               this.title = "搜索商品";
               // this.searchData();
          } else{
               this.title = options.name ? options.name : "商品列表";
               if (options.id) {
                    switch (options.type) {
                         case "2":
                              this.searchForm.person2 = options.id;
                              break;
                         case "3":
                              this.searchForm.person3 = options.id;
                              break;
                         default:
                              this.searchForm.person1 = options.id;
                              break;
                    }
               }
               // this.searchData();
          }
     },
     onShow() {
          if (this.$refs.WaterfallRef) {
               this.$refs.WaterfallRef.upDate()
          }
     },
     methods: {
          //优惠券的查看详情跳转过来
     

          handleOnfocus(){
               const history = uni.getStorageSync('history_list')
               this.showHistory = history && history.length > 0;
          },
          //点击历史的数据
          handleSearch(data) {
               this.searchForm.search = data.value 
               this.searchData()
            console.log('搜索内容:', data.value)
    
          },
          generateSKU(val) {
               if (val.attribute_state == 2) {  //SKU的
                    this.$refs.popupComponent.handlerApply()

                    val.skuDetailList.forEach(item => {
                         const goodsNum = parseInt(item.goods_num);
                         item.disabled = goodsNum <= 0;
                    });
                    this.goods = val
               }
          },

          goodsNum(goods_num, more_num) {
               let result = 0;
               if (goods_num > 10) {
                    if (more_num === 0) {
                         result = 100; // 当more_num为0时，返回100%
                    } else {
                         result = goods_num / more_num;
                         if (result <= 1) {
                              result = Math.round(result * 100);
                         }
                    }
               }

               return result;
          },
          buttonClass(item) {
               if (item.num === 0) {
                    return true;
               }
               if (item.count > 0) {
                    return false;
               }
          },
          //查看商品详情
          toDetail(id) {
               uni.navigateTo({
                    url: "/pages/mer/goods/details/details?id=" + id,
               });
          },
          //下拉刷新
          async pullDownRefresh() {
               this.isRefresh = true;
               await this.searchData();
               this.isRefresh = false;
          },
 
            // 搜索处理函数
            async searchData() {
               this.showHistory = false
               this.$refs.historyPopup.saveSearchHistory(this.searchForm.search)
               try {
                    // 重置搜索状态
                    this.resetSearch();
                    
                    // 执行搜索
                    await this.getGoodsList();
                    
                    // 更新瀑布流布局
                    this.$nextTick(() => {
                         if (this.$refs.WaterfallRef) {
                              this.$refs.WaterfallRef.upDate();
                         }
                    });
               } catch (error) {
                    console.error('搜索出错:', error);
                    uni.showToast({
                         title: '搜索失败，请重试',
                         icon: 'none'
                    });
               }
          },
          //关闭规格弹窗
          closeSku() {
               this.showSelectSku = false;
          },
          //添加商品到购物车
          async addToCar(index) {
               if (this.goodsList[index].attribute == 2) {
                    this.goods = {
                         ...this.goodsList[index],
                         goods_image: this.goodsList[index].path,
                         goods_num: 999,
                    };
                    this.showSelectSku = true;
               } else {
                    const res = await this.$mutations.setShoppingCar(
                         {
                              goods_id: this.goodsList[index].goods_id,
                              num: 1,
                         },
                         1
                    );
                    if (res) {
                         this.showSelectSku = false;
                    }
               }
          },
          //点击搜索
          search() {
               uni.navigateTo({
                    url: "../product/productList/productList?type=1",
               });
          },
             // 重置搜索相关状态
             resetSearch() {
               this.goodsList = [];
               this.searchForm.page = 1;
               this.canLoad = true;
               this.isLoading = false;
               this.goods_id_gather = "";
               this.class_id = "";
               // 重置瀑布流组件
               if (this.$refs.WaterfallRef) {
                    this.$refs.WaterfallRef.upDate();
               }
          },
          //获取商品
          getGoodsList() {
               return new Promise(async (resolve) => {
                    if (this.isLoading || !this.canLoad) return resolve(false);
                    this.isLoading = true;
                    this.searchForm = Object.assign(this.searchForm, { 
                         class_id:this.class_id,
                         store_id: this.$store.mallStoreId,
                         goods_id_gather: this.goods_id_gather 
                    })
                    console.log('请求参数:', this.searchForm)
                    try {
                         const { status, data, goods, message } = await this.$request(
                              "SmallProgramApi/Goods/goodsStatic_v1",
                              this.searchForm
                         );
                         console.log('请求结果:', { status, data, goods, message })

                         if (status != 1) {
                              uni.showToast({
                                   title: message || '获取商品失败',
                                   icon: "none",
                              });
                              return resolve(false);
                         }

                         // 重置或初始化商品列表
                         if (this.searchForm.page == 1) {
                              this.goodsList = goods || [];
                         } else {
                              this.goodsList.push(...(goods || []));
                         }    

                         console.log('更新后的goodsList:', this.goodsList)

                         if (!goods || !goods.length) {
                              this.canLoad = false;
                         }

                         this.searchForm.page++;
                         this.goodsList.forEach((item) => {
                              let matchedItem = this.$store.merShoppingGoodsList.find(
                                   (el) => el.goods_id === item.id
                              );
                              if (matchedItem) {
                                   item.num = matchedItem.num;
                              } else {
                                   item.num = 0;
                              }
                         });
                         
                         this.isLoading = false;
                         resolve(true);
                    } catch (error) {
                         console.error('获取商品列表出错:', error);
                         uni.showToast({
                              title: '获取商品列表失败',
                              icon: "none",
                         });
                         this.isLoading = false;
                         resolve(false);
                    }
               });
          },



     },
};
</script>

<style lang="scss">
.bottom-message {
     color: #ccc;
     font-size: 24rpx;
     // background-color: #fff;
     width: 100%;
     padding: 10rpx 0;
}

.line {
     width: 40%;
     height: 1px;
     background-color: #ccc;
}



.search-box {
     height: 88rpx;
     padding: 12rpx 24rpx;
     box-sizing: border-box;
     background-color: #ffffff;
     box-shadow: 0 0 16rpx rgba(0, 0, 0, 0.05);
     z-index: 100;

     .search-content {
          height: 100%;
          width: 100%;
          padding: 0 0 0 24rpx;
          border: 2rpx solid var(--primary-color);
          border-radius: 34rpx;
          box-sizing: border-box;
          background-color: #ffffff;

          .search-icon {
               font-size: 28rpx;
               color: #999999;
          }

          .search-input {
               flex: 1;
               font-size: 28rpx;
               line-height: 48rpx;
               color: #333333;
               margin: 0 10rpx;
               height: 48rpx;
          }

          .search-btn {
               width: 124rpx;
               height: 100%;
               font-size: 28rpx;
               color: #ffffff;
               text-align: center;
               line-height: 48rpx;
               background-color: var(--primary-color);
               border-radius: 32rpx;
               margin-right: -1rpx;
          }
     }
}

.scroll-view {
     //     background: linear-gradient(180deg, #ffffff 0%, #f8f8f8 100%);
     background: #F0F2EE;
}
</style>
